import {Component, OnInit} from '@angular/core';
import {DepartmentManageService} from './department-manage.service';
import {DepartInfo, TreeNodeInterface} from './domain/depart';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {SelfValidators} from '../../../utils/self.validators';
import {NzModalService} from 'ng-zorro-antd';
import {CopyUtil} from '../../../utils/copy.util';
import {StatusEnum} from '../../../core/enum/status.enum';
import {StorageUtil} from '../../../utils/storage.util';

@Component({
    selector: 'app-department-manage',
    templateUrl: './department-manage.component.html',
    styleUrls: ['./department-manage.component.scss'],
    providers: [DepartmentManageService]
})
/**
 * @author zhouxin
 * @date 2019-04-20
 * @description 部门管理
 */
export class DepartmentManageComponent implements OnInit {

    listOfMapData = [];
    mapOfExpandedData: { [key: string]: TreeNodeInterface[] } = {};
    isVisible = false;
    departInfos: DepartInfo = new DepartInfo();
    validateForm: FormGroup;
    headTeacherList = [];

    /**
     * 如果是新增根节点，默认去掉清楚按钮
     */
    rootClear = true;
    showBtns = 1; // 当前登录人是否有操作权限,0-隐藏 1-显示

    constructor(private departmentManageService: DepartmentManageService,
                private fb: FormBuilder,
                private modalService: NzModalService) {
    }

    ngOnInit() {
        this.pageList();
        this.initForm();
        // this.showBtns = StorageUtil.getLocalStorage('roleManager');
    }

    /**
     * 校验
     */
    initForm() {
        this.validateForm = this.fb.group({
            parentId: [this.departInfos.parentId, []],
            name: [this.departInfos.name, [Validators.required]],
            leader: [this.departInfos.leader, []],
            leaderList: [this.departInfos.leaderList, []],
            telphone: [this.departInfos.telphone, []],
            fax: [this.departInfos.fax, []]
        });
    }

    /**
     * 列表数据
     */
    pageList() {
        this.departmentManageService.getList({}).subscribe(res => {
            if (res.status === StatusEnum.SUCCESS) {
                this.listOfMapData = res.datas;
                this.listOfMapData.forEach(item => {
                    this.mapOfExpandedData[item.key] = this.convertTreeToList(item);
                });
            }
        });
    }

    /**
     * 表格事件
     */
    collapse(array: TreeNodeInterface[], data: TreeNodeInterface, $event: boolean): void {
        if ($event === false) {
            if (data.children) {
                data.children.forEach(d => {
                    const target = array.find(a => a.key === d.key)!;
                    target.expand = false;
                    this.collapse(array, target, false);
                });
            } else {
                return;
            }
        }
    }

    /**
     * 表格事件
     */
    convertTreeToList(root: object): TreeNodeInterface[] {
        const stack: any[] = [];
        const array: any[] = [];
        const hashMap = {};
        stack.push({...root, level: 0, expand: false});

        while (stack.length !== 0) {
            const node = stack.pop();
            this.visitNode(node, hashMap, array);
            if (node.children) {
                for (let i = node.children.length - 1; i >= 0; i--) {
                    stack.push({...node.children[i], level: node.level + 1, expand: false, parent: node});
                }
            }
        }
        return array;
    }

    /**
     * 表格事件
     */
    visitNode(node: TreeNodeInterface, hashMap: { [key: string]: any }, array: TreeNodeInterface[]): void {
        if (!hashMap[node.key]) {
            hashMap[node.key] = true;
            array.push(node);
        }
    }


    /**
     * 新增
     */
    clickAdd() {
        this.departInfos = new DepartInfo();
        this.initForm();
        this.getTeachList();
        this.isVisible = true;
    }

  /**
   * 获取教师
   */
  getTeachList() {
    this.departmentManageService.getTeachList().subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.headTeacherList = res.datas;
      }
    });
  }

    /**
     * 编辑
     */
    editDept(data) {
        this.getTeachList();
        this.departInfos = new DepartInfo();
        this.departInfos.id = data.key;
        this.departInfos.name = data.title;
        this.departInfos.telphone = data.telphone;
        this.departInfos.fax = data.fax;
        this.departInfos.parentId = data.parent ? data.parent.key : '0';
        if (data.leaderId !== 'undefined') {
          this.departInfos.leaderId = data.leaderId.split(',');
        }
        if (data.leaderIdStr) {
          this.departInfos.leaderList = data.leaderIdStr.split(',');
        }
        this.isVisible = true;
    }

    /**
     * 新增字节点
     */
    addDeptOwn(data) {
        this.departInfos = new DepartInfo();
        this.departInfos.parentId = data.key;
        this.isVisible = true;
        this.initForm();
    }

    /**
     * 编辑提交
     */
    dealEditSub(): void {
        const arr = [];
        (this.departInfos.leaderList || []).map(item => {
          arr.push({
            leaderId: item
          });
        });
        this.departmentManageService.update({
          ...this.departInfos,
          leaderList: arr
        }).subscribe(res => {
            if (res.status === StatusEnum.SUCCESS) {
                this.isVisible = false;
                this.pageList();
            }
        });
    }

    /**
     * 新增提交
     */
    dealAddSub(): void {
        const arr = [];
        (this.departInfos.leaderList || []).map(item => {
          arr.push({
            leaderId: item
          });
        });
        this.departmentManageService.submit({
          ...this.departInfos,
          leaderList: arr
        }).subscribe(res => {
            if (res.status === StatusEnum.SUCCESS) {
                this.isVisible = false;
                this.pageList();
            }
        });
    }

    /**
     * 提交保存
     */
    submit() {
        // if (this.departInfos.leaderId && this.departInfos.leaderId.length > 0 ) {
        //   let val = '';
        //   this.departInfos.leaderId.forEach((item, index) => {
        //     if (index !== this.departInfos.leaderId.length - 1) {
        //       val += item + ',';
        //     } else {
        //       val += item;
        //     }
        //   });
        //   this.departInfos.leaderId = this.departInfos.leaderId.toString();
        // }
        this.departInfos.leaderId = this.departInfos.leaderId + '';
        if (!this.departInfos.parentId) {
            this.departInfos.parentId = '0';
            this.departInfos.id ? this.dealEditSub() : this.dealAddSub();
        } else {
            this.departInfos.id ? this.dealEditSub() : this.dealAddSub();
        }
    }

    /**
     * 删除
     * @param ids id
     */
    deleteDept(ids) {
        const data = {
            id: ids
        };
        this.departmentManageService.delete(data).subscribe(res => {
            if (res.status === StatusEnum.SUCCESS) {
                this.pageList();
            }
        });
    }
}
